package com.example.logisticsingle.authorization;


import com.example.logisticsingle.Service.LoginService;
import com.example.logisticsingle.constants.ResponseEnum;
import com.example.logisticsingle.dto.Result;
import com.example.logisticsingle.model.LoginLog;
import com.example.logisticsingle.requsest.RequestUtils;
import com.example.logisticsingle.utils.JsonUtils;
import com.example.logisticsingle.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 访问被拒绝处理

 *
 */
@Slf4j

public class AuthAccessDeineHandler implements AccessDeniedHandler {
    @Autowired
    private LoginService loginService;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
//		if(request.getHeader("User-Agent").startsWith("Mozilla")) {
//
//		}else {
//
//		}
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        Result<?> result = ResultUtils.failure(ResponseEnum.AUTHORITY_FORBIDDEN);
        //记录日志
        String ip = RequestUtils.getIPAddress(request);
        LoginLog loginLog = new LoginLog();
        loginLog.setUserName(request.getParameter("username"));
        loginLog.setIpaddr(ip);
        loginLog.setBrowser("");
        loginLog.setLoginLocation("");
        loginLog.setLoginTime(new Date());
        loginLog.setOs("");
        loginLog.setPhoneBrand("");
        loginLog.setPhoneModel("");
        loginLog.setPhoneOs("");
        loginLog.setStatus("0");
        loginLog.setMsg(result.getMessage());
        log.info("insert login log:{}",loginLog);
        loginService.insertLoginLog(loginLog);
        response.getWriter().write(JsonUtils.toJson(result));

    }
}
